from abc import ABC
from types import ModuleType
from typing import Optional, List
from importlib import import_module
from vnpy.trader.object import HistoryRequest, TickData, BarData, FutBasicData, FutBasicRequest, FutMappingData
# from vnpy.trader.setting import SETTINGS
from pandas import DataFrame


class BaseDatafeed(ABC):
    """
    Abstract datafeed class for connecting to different datafeed.
    """

    def init(self) -> bool:
        """
        Initialize datafeed service connection.
        """
        pass

    def query_bar_history(self, req: HistoryRequest) -> Optional[DataFrame]:
        """
        Query history bar data.
        """
        pass

    def query_tick_history(self, req: HistoryRequest) -> Optional[List[TickData]]:
        """
        Query history tick data.
        """
        pass

    def query_fut_basic(self, req: FutBasicRequest) -> Optional[List[FutBasicData]]:
        """
        Query Fut basic data.
        """
        pass

    def query_fut_mapping(self, ts_code: str, trade_date: str, start_date: str, end_date: str) \
            -> Optional[List[FutMappingData]]:
        """
        Query Fut Mapping data.
        """
        pass

    def get_all_securities(self) -> DataFrame:
        """
        get_all_securities
        """
        pass


datafeed: BaseDatafeed = None


def get_datafeed(datafeed_name: str = "tushare") -> BaseDatafeed:
    """"""
    # Return datafeed object if already inited
    global datafeed
    if datafeed:
        return datafeed

    # Read datafeed related global setting
    # datafeed_name: str = SETTINGS["datafeed.name"]
    module_name: str = f"vnpy.feeds.{datafeed_name}"
    print(module_name)

    # Try to import datafeed module
    try:
        module: ModuleType = import_module(module_name)
    except ModuleNotFoundError:
        print(f"找不到数据服务驱动{module_name}，使用默认的tushare数据服务")
        module: ModuleType = import_module("vnpy.feeds.tushare")

    # Create datafeed object from module
    datafeed = module.Datafeed()
    return datafeed
